package com.wangp.mywrite.s_netty.nio.ch3.block_mode;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.wangp.mywrite.s_netty.nio.ch1.ByteBufferUtil.debugRead;

/**
 * @author tooStronger
 * @date 2023/3/16
 */
@Slf4j
public class Server {

    public static void main(String[] args) throws IOException {
        // 使用 nio 理解阻塞模式，单线程.

        // 0. 创建byteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(16);
        // 1. 创建服务器
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 2. 绑定监听端口
        serverSocketChannel.bind(new InetSocketAddress(8080));
        // 3. 建立一个链接的集合
        List<SocketChannel> channels = new ArrayList<>();
        while (true) {
            // 4. accept建立连接, socket channel 与客服端进行通信
            log.info("connecting...");
            SocketChannel sc = serverSocketChannel.accept(); // 阻塞方式，线程停止运行
            log.info("connected...{}", sc);
            channels.add(sc);
            // 5. 接受客户端发送的数据
            for (SocketChannel channel : channels) {
                log.info("before read...{}", channel);
                channel.read(byteBuffer);  // 阻塞方法
                byteBuffer.flip();
                debugRead(byteBuffer);
                byteBuffer.clear();
                log.info("after read...{}", channel);
            }
        }
    }
}
